package com.zch.socket.socket.server;




import org.junit.Test;

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 服务端
 */
public class SocketServer {
    ExecutorService threadPool = Executors.newFixedThreadPool(8);
    @Test
    public void test1() throws Exception{
        int port=1066;//端口号
        //服务端先创建serverSocket；
        ServerSocket serverSocket=new ServerSocket(port);

        while (true){
            Socket socket=serverSocket.accept();
         threadPool.submit(new Runnable() {
             @Override
             public void run() {
                 try{
                     // server将一直等待连接的到来
                       //System.out.println("server阻塞 等待连接的到来………………");

                        //System.out.println("server接受到请求并成功创建了Socket连接");

                     // 建立好连接后，从socket中获取输入流，从输入流里读取客户端的请求数据
                     InputStream inputStream = socket.getInputStream();
                     ObjectInputStream objectInputStream=new ObjectInputStream(inputStream);
                     OutputStream outputStream=socket.getOutputStream();
                     ObjectOutputStream objectOutputStream=new ObjectOutputStream(outputStream);
                     String str=(String)objectInputStream.readObject();
                     System.out.println("收到客户端数据" + str);
                     //服务端返回消息给客户端用输出流
                     objectOutputStream.writeObject(str);
                     //关闭
                     inputStream.close();
                     outputStream.close();
                     //socket.close();
                     //serverSocket.close();
                 }catch (Exception e){

                 }
             }
         });
        }

    }
}
